package com.wolfking.converter.transform.extend;

import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.wolfking.converter.transform.AbstractExtendTransform;
import com.wolfking.converter.util.CaesarUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
public class JsonExtractMaskTransform extends AbstractExtendTransform<String> {


    private final String format;

    private String mask = "";

    public JsonExtractMaskTransform(){
        this("");
    }


    public JsonExtractMaskTransform(String format) {
        String[] split = format.split(",");
        this.format = split[0];
        if (split.length > 1) {
            mask = split[1];
        }
    }

    @Override
    public boolean canTransform(Class<?> fieldType) {
        return true;
    }

    @Override
    public String transform(Object value) {
        if (Objects.isNull(value)) {
            return "";
        }
        String beforeValue;
        if (value instanceof String) {
            beforeValue = value.toString();
        } else if (value instanceof byte[]) {
            beforeValue = new String((byte[]) value, StandardCharsets.UTF_8);
        } else {
            beforeValue = value.toString();
        }

        if (CaesarUtil.isEncrypted(beforeValue)) {
            beforeValue = CaesarUtil.decode(beforeValue);
        }

        try {

            JsonElement element = JsonParser.parseString(beforeValue);
            if (!element.isJsonArray() && !element.isJsonObject()) {
                return beforeValue;
            }
            List<String> maskString = JsonExtractTransform.extractString(element, format);
            if (StringUtils.isNotBlank(mask)) {
                StringMaskTransform stringMaskTransform = new StringMaskTransform(mask);
                maskString = maskString.stream().map(stringMaskTransform::transform)
                        .map(Object::toString)
                        .collect(Collectors.toList());
            }
            return String.join(",", maskString);
        } catch (Exception e) {
            log.warn("", e);
            return beforeValue;
        }
    }

    @Override
    public String getExampleConfig() {
        return "a.b.c,name";
    }

    @Override
    public String getExampleConfigDesc() {
        return "用逗号隔开，第一个参数是json路径，第二个是脱敏的类型，包括 name,id_card,bank_card,mobile 四种";
    }
}
